﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace CYTS.Aoyou.Framework.Utility
{
    /// <summary>
    /// 类型帮助类
    /// </summary>
    public class TypeHelper
    {
        /// <summary>
        /// 判断指定类型是否实现了指定接口
        /// </summary>
        /// <param name="classType"></param>
        /// <param name="interfaceType"></param>
        /// <returns></returns>
        public static bool IsRealizeInterface(Type classType, Type interfaceType)
        {
            if (classType == null)
            {
                throw new Exception("指定类型不能为null");
            }

            Type[] interfaceTypes = classType.GetInterfaces();
            foreach (Type t in interfaceTypes)
            {
                if (t == interfaceType)
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 断指定类型是否继承了指定基类
        /// </summary>
        /// <param name="classType"></param>
        /// <param name="baseType"></param>
        /// <returns></returns>
        public static bool IsInheritBase(Type classType, Type baseType)
        {
            if (classType == null)
            {
                throw new Exception("指定类型不能为null");
            }

            Type realBaseType = classType.BaseType;
            if (realBaseType == baseType)
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// 获取一个Wcf类型的ServiceContract接口类型
        /// </summary>
        /// <param name="type">服务类型</param>
        /// <returns>返回服务类的ServiceContract接口类型，如果找不到则返回Null</returns>
        public static Type GetServiceContractType(Type type)
        {
            if (type == null)
            {
                throw new Exception("服务类型不能为null");
            }

            Type[] interfaceTypes = type.GetInterfaces();
            foreach (Type it in interfaceTypes)
            {
                object[] objs = it.GetCustomAttributes(typeof(ServiceContractAttribute), true);
                if (objs != null)
                {
                    foreach (object obj in objs)
                    {
                        if (obj is ServiceContractAttribute)
                        {
                            return it;
                        }
                    }
                }
            }

            return null;
        }
    }
}
